package com.hx.voice.recognition.auth.client.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hx.voice.recognition.auth.client.annotation.IgnoreUserToken;
import com.hx.voice.recognition.auth.client.config.UserAuthConfig;
import com.hx.voice.recognition.auth.client.jwt.UserAuthUtil;
import com.hx.voice.recognition.auth.common.util.jwt.IJWTInfo;
import com.hx.voice.recognition.common.context.BaseContextHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @descripe：用户授权拦截器，每次请求时获取用户信息，并存放在本次线城池中，供业务逻辑使用
 * @company：南京华讯方舟通讯设备有限公司
 * @author：zhoujinbing
 * @time：2019/6/19 15:24
 * @version：V1.0
 */
@Slf4j
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        //配置该注解，说明不进行用户拦截
        IgnoreUserToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
        if(annotation == null)
        {
            annotation = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
        }
        if(annotation != null)
        {
            //忽略放行，不进行验证
            return super.preHandle(request, response, handler);
        }

        String token = request.getHeader(userAuthConfig.getTokenHeader());
        if(StrUtil.isEmpty(token))
        {
            if(request.getCookies() != null)
            {
                for (Cookie cookie : request.getCookies()) {
                    if(cookie.getName().equals(userAuthConfig.getTokenHeader()))
                    {
                        token = cookie.getValue();
                    }
                }
            }
        }

        IJWTInfo infoFormToken = userAuthUtil.getInfoFormToken(token);
        BaseContextHandler.setUsername(infoFormToken.getUniqueName());
        BaseContextHandler.setName(infoFormToken.getName());
        BaseContextHandler.setUserID(infoFormToken.getId());
        return super.preHandle(request,response,handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}